<?php
namespace App\Logic;

class ProductLogic
{
	public $m;
	//json字段定义，下面会自动处理输入输出
	private $jsonField = array(
		'cover'			=>	'object',
		'custom'		=>	'array',
	);

	public function __construct()
	{
		$this->m = M('product');
	}

	public function ls()
	{
		$where = array();

		//对分类搜索特殊处理，去掉id后面的
		cate_where();
		//自动构造搜索条件
		$where = parseWhere();

		//列表
		$page = isset($_POST['page']) ? $_POST['page'] : 1;
		$page = max($page, 1);
		$size = isset($_POST['size']) ? $_POST['size'] : 15;
		$start = $page * $size - $size;


		$prop = $_POST['prop'] ? $_POST['prop'] : 'id';
		if($prop == 'cate') $prop = 'cate_id';
		if($_POST['order'] == 'desc') {
			$order = 'DESC';
		}elseif($_POST['order'] == 'asc') {
			$order = 'ASC';
		}
		if($order) {
			$this->m->order("$prop $order");
		}
		$data = $this->m->where($where)->limit($start, $size)->select();

		foreach ($data as &$d) {
			$d['cate'] = getCate($d['cate_id']);
			foreach($this->jsonField as $field => $type) {
				$d[$field] = json_decode($d[$field], true);
				if(!$d[$field] && $type == 'object') $d[$field] = new \stdClass();
				if(!$d[$field] && $type == 'array') $d[$field] = array();
			}
		}
		$total = $this->m->where($where)->count();

		return array('st' => 1, 'data' => $data, 'total' => $total);
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->m->find($id);
		$row['price'] = (float) $row['price'];
		foreach($this->jsonField as $field => $type) {
			$row[$field] = json_decode($row[$field], true);
			if(!$row[$field] && $type == 'object') $row[$field] = new \stdClass();
			if(!$row[$field] && $type == 'array') $row[$field] = array();
		}
		$row['attend'] = \App\Logic\AttendLogic::ls(array('module' => 'product', 'pk' => $row['id']));
		return $row;
	}

	public function save($post)
	{
		$id = (int) $post['id'];
		foreach($this->jsonField as $field => $type) {
			$post[$field] = json_encode($post[$field], 256);
			if(!$post[$field] && $type == 'object') $post[$field] = '{}';
			if(!$post[$field] && $type == 'array') $post[$field] = '[]';
		}
		if($id) {
			$rs = $this->m->where("id = $id")->save($post);
			if($rs === false) {
				json(0, '保存错误');
			}
		}else{
			$post['admin_id'] = ADMIN_ID;
			$post['admin_name'] = getAdmin(ADMIN_ID);
			$id = $this->m->add($post);
			if($id === false) {
				json(0, '添加错误');
			}
		}
		//保存附件
		\App\Logic\AttendLogic::save('product', $id, $post['attend']);
		return true;
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) json(0, '参数错误');
		$rs = $this->m->where("id = $id")->delete();
		if($rs === false) {
			return array('st' => 0, 'msg' => '删除失败');
		}else{
			return array('st' => 1);
		}
	}
}